/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ca.trader.user;

import ca.trader.enterprisebeans.UserBeanLocal;
import ca.trader.except.InvalidHttpRequestException;
import ca.trader.except.UserDoesNotExistException;
import ca.trader.logger.TraderLogger;
import ca.trader.utils.DebugUtils;
import ca.trader.utils.HttpConsts;
import ca.trader.utils.HttpUtils;
import ca.trader.utils.PasswordUtils;
import ca.trader.utils.URLUtils;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Ahsan
 */
@WebServlet(name = "DoAuthenticate", urlPatterns =
{
	 "/DoAuthenticate"
})
public class DoAuthenticate extends HttpServlet
{
	 private static final String _className = DoAuthenticate.class.getName();

	 private static final String PARAM_EMAIL = "email";
	 private static final String PARAM_PASSWORD = "password";
	 private static final String PARAM_REMEMBER = "remember";

	 @EJB
	 UserBeanLocal userBean;	 
	 
	 /**
	  * Processes requests for both HTTP
	  * <code>GET</code> and
	  * <code>POST</code> methods.
	  *
	  * @param request servlet request
	  * @param response servlet response
	  * @throws ServletException if a servlet-specific error occurs
	  * @throws IOException if an I/O error occurs
	  */
	 protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	 {

		  String _methodName = "processRequest";

		  TraderLogger.logInfo(_className, _methodName, "Starting servlent: " + this.getServletName());


		  HttpSession session = request.getSession(true);

		  if (HttpUtils.wasUserAuthenticationSuccess(session))
		  {
			   String authenticatedUserEmail = session.getAttribute(HttpConsts.SESSION_ATTRIBUTE_AUTHENTICATED_USER_EMAIL).toString();

			   TraderLogger.logInfo(_className, _methodName, "User already authenticated: " + authenticatedUserEmail);
			   TraderLogger.logInfo(_className, _methodName, "Exiting servlent: " + this.getServletName());

			   response.sendRedirect(HttpConsts.INDEX_JSP_PAGE);

			   return;
		  }


		  boolean wasUnknownFailure = false;
		  boolean wasSuccess = false;

		  String failureReason = "";
		  String unknownReasonStackTrace = "";


		  String userEmail = "";

		  try
		  {


			   boolean rememberUser = false;
			   if (request.getParameter(PARAM_REMEMBER) != null)
			   {
				    if (request.getParameter(PARAM_REMEMBER).equals("true"))
				    {
						TraderLogger.logInfo(_className, _methodName, "User requested to remember");
						rememberUser = true;
				    }

			   }

			   TraderLogger.logInfo(_className, _methodName, "Validating POST PARAMETERS");

			   if (request.getParameter(PARAM_EMAIL) == null || request.getParameter(PARAM_PASSWORD) == null)
			   {
				    throw new InvalidHttpRequestException("Invalid Request");
			   }


			   String userPassword = request.getParameter(PARAM_PASSWORD).trim();
			   userEmail = request.getParameter(PARAM_EMAIL).trim();


			   User user = userBean.getUserWithEmail(userEmail);


			   if (!PasswordUtils.TestCryptedPassword(userPassword, user.getCryptedPassword()))
			   {
				    failureReason = "Invalid Password";
			   }
			   else
			   {
				    //request.login(user.getEmail(), userDbCryptedPassword.toString());

				    HttpUtils.setUserAuthenticated(session, user);

				    TraderLogger.logInfo(_className, _methodName, "Successfully authenticated user: " + userEmail);


				    if (rememberUser)
				    {
						TraderLogger.logInfo(_className, _methodName, "User requested to remember, attempting to remember");
						userBean.rememberUser(response, user);
				    }

				    TraderLogger.logInfo(_className, _methodName, "Exiting servlent: " + this.getServletName());

				    response.sendRedirect(HttpConsts.INDEX_JSP_PAGE);

				    wasSuccess = true;

				    return;
			   }

		  }
		  catch (InvalidHttpRequestException e)
		  {
			   failureReason = "Invalid request.  Please request from " + URLUtils.getMainWebpage(request) + "/" + HttpConsts.LOGIN_JSP_PAGE;

		  }
		  catch (UserDoesNotExistException e)
		  {
			   failureReason = e.getMessage();
		  }
		  catch (Exception e)
		  {

			   failureReason = "Unknown error: " + e.getMessage();

			   wasUnknownFailure = true;
			   unknownReasonStackTrace = DebugUtils.getStackTraceAsString(e);

		  }
		  if (!wasSuccess)
		  {
			   TraderLogger.logInfo(_className, _methodName, "Unable to authenticate user: " + failureReason);

			   if (wasUnknownFailure)
			   {
				    TraderLogger.logSevere(_className, _methodName, failureReason, unknownReasonStackTrace);
			   }

			   session.setMaxInactiveInterval(3);

			   session.setAttribute(HttpConsts.SESSION_ATTRIBUTE_USER_AUTHENTICATED, false);
			   session.setAttribute(HttpConsts.SESSION_ATTRIBUTE_USER_NOT_AUTHENTICATED_REASON, failureReason);
			   session.setAttribute(HttpConsts.SESSION_ATTRIBUTE_USER_NOT_AUTHENTICATED_EMAIL, userEmail);

			   TraderLogger.logInfo(_className, _methodName, "Exiting servlent: " + this.getServletName());

			   TraderLogger.exiting();
			   response.sendRedirect(HttpConsts.LOGIN_JSP_PAGE);

		  }

	 }

	 // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
	 /**
	  * Handles the HTTP
	  * <code>GET</code> method.
	  *
	  * @param request servlet request
	  * @param response servlet response
	  * @throws ServletException if a servlet-specific error occurs
	  * @throws IOException if an I/O error occurs
	  */
	 @Override
	 protected void doGet(HttpServletRequest request, HttpServletResponse response)
		    throws ServletException, IOException
	 {
		  processRequest(request, response);
	 }

	 /**
	  * Handles the HTTP
	  * <code>POST</code> method.
	  *
	  * @param request servlet request
	  * @param response servlet response
	  * @throws ServletException if a servlet-specific error occurs
	  * @throws IOException if an I/O error occurs
	  */
	 @Override
	 protected void doPost(HttpServletRequest request, HttpServletResponse response)
		    throws ServletException, IOException
	 {
		  processRequest(request, response);
	 }

	 /**
	  * Returns a short description of the servlet.
	  *
	  * @return a String containing servlet description
	  */
	 @Override
	 public String getServletInfo()
	 {
		  return "Short description";
	 }// </editor-fold>

}
